package com.foredu.fiqs.persist.hibernate;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

import com.foredu.fiqs.domain.Role;
import com.foredu.fiqs.domain.User;
import com.foredu.fiqs.persist.IRoleDao;

public class HibernateRoleDao extends HibernateAbstractDao<Role, Integer>
		implements IRoleDao {

	private static final long serialVersionUID = 1L;

	public HibernateRoleDao() {
		super(Role.class);
	}

	@SuppressWarnings("unchecked")
	@Override
	public Role findRoleByName(String name) {
		List<Role> roleList = this.getHibernateTemplate().find(
				"from Role role where role.name = ?", name);
		Role role = null;
		if (roleList != null && roleList.size() > 0) {
			role = roleList.get(0);
		}
		return role;
	}

	@Override
	public List<User> findUsersByRoleName(String roleName) {
		List<User> userList = new ArrayList<User>();
		Role role = findRoleByName(roleName);
		Set<User> userSet = role.getUsers();
		Iterator<User> setIter = userSet.iterator();
		while (setIter.hasNext()) {
			User user = (User) setIter.next();
			userList.add(user);
		}
		return userList;
	}

}
